package liming.ai.code.v4.data;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class Context {
    String query;
    Map<FileInfo,Integer> fileInfoIntegerMap=new HashMap<>();
//    Set<FileInfo> fileInfos= new HashSet<>();
    public Context(String query){
        this.query = query;
    }

    public void add(FileInfo fileInfo){
        fileInfoIntegerMap.put(fileInfo,fileInfo.getVersion());
    }

    //获取目标项目路径下已有内容并加载到上下文中
    public Context initContext(){
        File javasFile = new File(BaseConfig.getJavasPath());
        File classesFile = new File(BaseConfig.getClassesPath());
        File mdsFile = new File(BaseConfig.getMdsFilePath());

        // 遍历Java源文件目录
        processDirectory(javasFile, ".java", BaseConfig.getJavasPath());
        // 遍历class编译文件目录
        processDirectory(classesFile, ".class", BaseConfig.getClassesPath());
        // 遍历md文档文件目录
        processDirectory(mdsFile, ".md", BaseConfig.getMdsFilePath());
        return this;
    }
    private void processDirectory(File directory, String extension, String basePath) {
        if (!directory.exists() || !directory.isDirectory()) return;
        try {
            Files.walk(directory.toPath())
                    .filter(Files::isRegularFile)
                    .filter(p -> p.toString().endsWith(extension))
                    .forEach(p -> {
                        try {
                            String relativePath = directory.toPath().relativize(p).toString();
                            String qualifiedName = relativePath
                                    .replace(File.separatorChar, '.')
                                    .substring(0, relativePath.length() - extension.length());

                            int lastDotIndex = qualifiedName.lastIndexOf('.');
                            String packageName = lastDotIndex > 0 ?
                                    qualifiedName.substring(0, lastDotIndex) : "";
                            String className = qualifiedName.substring(lastDotIndex + 1);

                            FileInfo fileInfo = new FileInfo(packageName, className);

                            // 如果已存在则更新版本，否则添加新条目
                            fileInfoIntegerMap.merge(fileInfo, 1, Integer::max);
                        } catch (Exception e) {
                            System.err.println("Error processing file: " + p + ", " + e.getMessage());
                        }
                    });
        } catch (IOException e) {
            System.err.println("Error walking directory: " + directory + ", " + e.getMessage());
        }
    }

    public String getQuery(){
        return query;
    }

    public boolean isVersion(FileInfo fileInfo){
        return !fileInfoIntegerMap.containsKey(fileInfo)||fileInfoIntegerMap.get(fileInfo)<fileInfo.getVersion();
    }

    public String getAllFileInfo(){
        if(fileInfoIntegerMap.isEmpty())
            return "当前无辅助文件\n";
        StringBuilder sb= new StringBuilder("当前辅助文件有:\n");
        fileInfoIntegerMap.forEach(((fileInfo, version) ->
                sb.append(fileInfo.getAllClassName()).append(" 版本:").append(version).append("\n")));
        return sb.toString();
    }

    public String getAllJavaFilePath(){
        StringBuilder sb= new StringBuilder("");
        fileInfoIntegerMap.forEach((fileInfo, integer) ->
                sb.append(" ").append(fileInfo.getJavaFile().getAbsolutePath()));
        return sb.toString();
    }

}
